/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.Arrays;

import com.hiddenequity.adextensions_service.CampaignAdExtensionResponseParser;
import com.hiddenequity.adextensions_service.CampaignAdExtensionService;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Communication;
import com.hiddenequity.utils.DataValidator;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class Act_SiteLinkExtensionOperation extends Act_Super{

	private String campaignName;
	
	private String campaignId;
	private String extensionId;
	
	private String[] initDisplayText = new String[10];
	private String[] initDestinationUrl = new String[10];

	private String[] displayText = new String[10];
	private String[] destinationUrl = new String[10];
	
	private LinearLayout ll_sitelinks;
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.super_operation_layout);
		
		((ViewStub) findViewById(R.id.stub_sitelinkextension_operation)).inflate();

        Intent intent = getIntent();
		
		extensionId = intent.getStringExtra("extensionId");
		campaignId = intent.getStringExtra("campaignId");
		campaignName = intent.getStringExtra("campaignName");
		
        title.setText(extensionId == null ? getString(R.string.title_sitelinkextension_add) : getString(R.string.title_sitelinkextension_edit));
        sub_title.setText(campaignName);
        sub_title.setVisibility(campaignName != null ? View.VISIBLE : View.GONE);

        filter.setVisibility(View.GONE);

		initDisplayText = intent.getStringArrayExtra("displayText");
		initDestinationUrl = intent.getStringArrayExtra("destinationUrl");
		
		ll_sitelinks = (LinearLayout) findViewById(R.id.ll_sitelinks);
		
		String displayTextValue;
		String destinationUrlValue;
		
		if(initDisplayText != null && initDestinationUrl != null){
			for(int i=0; i<10; i++){
				try {
					displayTextValue = initDisplayText[i];
					destinationUrlValue = initDestinationUrl[i];
				} catch (Exception e) {
					e.printStackTrace();
				}
				displayTextValue = initDisplayText[i];
				destinationUrlValue = initDestinationUrl[i];
				
				if(displayTextValue != null){
					addLink(displayTextValue, destinationUrlValue, i+1);
				}
			}
		} else {
			addLink(null, null, 1);
		}

		((Button) findViewById(R.id.btn_add_link))
			.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				int childCount = ll_sitelinks.getChildCount();
				if(childCount == 10)
					return;
				addLink(null, null, childCount+1);
			}
		});
		
	}//onCreate
	
	
	
	/*
	 * Update links number after delete
	 */
	private void updateLinkNumber(){
		int childCount = ll_sitelinks.getChildCount();
		View ll_link;
		TextView tv;
		for(int i=0; i<childCount; i++){
			ll_link = (LinearLayout) ll_sitelinks.getChildAt(i);
			tv = (TextView) ll_link.findViewById(R.id.lbl_sitelink_exstension);
			tv.setText(getString(R.string.lbl_sitelinkext) + " " + (i+1));
		}
	}//updateLinkNumber
	
	
	
	/*
	 * Add link to view
	 */
	private void addLink(String displayText, String destignationUrl, int linkNumber){
		// Inflate layout
		LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = li.inflate(R.layout.link_siltelinks_extension, null, false);
		
		// Get ref to views
		TextView lbl_sitelink_exstension = (TextView) v.findViewById(R.id.lbl_sitelink_exstension);
		EditText edit_sitelinkext_display = (EditText) v.findViewById(R.id.edit_sitelinkext_display);
		Spinner spin_sitelink_url_schema = (Spinner) v.findViewById(R.id.spin_sitelink_url_schema);
		EditText edit_sitelinkext_url = (EditText) v.findViewById(R.id.edit_sitelinkext_url);
		
		// Populate link title
		lbl_sitelink_exstension.setText(lbl_sitelink_exstension.getText().toString() + " " + linkNumber);
		
		// Populate display text
		edit_sitelinkext_display.setText(displayText);

		// Populate destination URL with spinner
		int position = 0;
		
		if(destignationUrl != null)
			if(destignationUrl.contains("http://")){
				edit_sitelinkext_url.setText(destignationUrl.replace("http://", ""));
				position = 0;
			} else {
				edit_sitelinkext_url.setText(destignationUrl.replace("https://", ""));
				position = 1;
			}
		
		inflateSpinner(spin_sitelink_url_schema, R.array.arr_urlSchemas, position);
		
		((Button) v.findViewById(R.id.btn_remove_link))
			.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				LinearLayout ll_wrapper = (LinearLayout) arg0.getParent();
				LinearLayout ll_link = (LinearLayout) ll_wrapper.getParent();
				LinearLayout ll_parent = (LinearLayout) ll_link.getParent();
				ll_parent.removeView(ll_link);
				updateLinkNumber();
			}
		});

		ll_sitelinks.addView(v);
	}//addLink
	

	
	/*
	 * Async operation
	 */
	private void runOperationAsync(final int operation, String message, boolean overlap) {

		//Stop if thread is alive
		if(thread.isAlive() && !overlap)
			return;
		
		//Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		//Check if Internet connection alive
		if(!isConnectionAvalable()){
			progressDialog.dismiss();
			return;
		}

		thread = new Thread(){
			public void run() {
				//Perform authentication
				new AuthService(Act_SiteLinkExtensionOperation.this, getApplication());
				//Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
							case OPERATION_SET_DATA:
								Act_SiteLinkExtensionOperation.this.siteLinkExtensionAddOperation();
								break;				
								
							case OPERATION_REMOVE_DATA:
								Act_SiteLinkExtensionOperation.this.siteLinkExtensionRemoveOperation();
								break;	
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				//Perform postoperation
				Act_SiteLinkExtensionOperation.this.runOnUiThread(new Runnable() {
					public void run() {
						
						progressDialog.dismiss();

						if (AuthService.authToken != null) {
							
							showOperationError(R.string.msg_title_error, responseErrorString);
							
							switch (operation) {
								case OPERATION_SET_DATA:
									if (responseErrorString == null)
										if (isChangesMade) {
											finishActivityWithResult(RESPONSE_REFRESH_REQUIRED);
										} else {
											finishActivityWithResult(RESPONSE_NO_REFRESH_REQUIRED);
										}
									break;
									
								case OPERATION_REMOVE_DATA:
									if (responseErrorString == null)
										runOperationAsync(OPERATION_SET_DATA, getString(R.string.progress_saving), true);
									break;
							}
							
						} else {
							Intent intent = new Intent(Act_SiteLinkExtensionOperation.this.getApplicationContext(),
									Act_Login.class);
							startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start(); 		
			
	}//runOperationAsync
	
	
	
	/*
	 * Remove operation
	 */
    protected void siteLinkExtensionRemoveOperation() {
    	
    	if(extensionId == null)
    		return;
    	
		if(Arrays.equals(displayText, initDisplayText) && Arrays.equals(destinationUrl, initDestinationUrl)){
    		isChangesMade = false;
    		return;
		}

		String resp = Communication.postSOAP(
				CampaignAdExtensionService.URL_CAMPAIGN_AD_EXTENSION_SERVICE, 
				CampaignAdExtensionService.removeSiteLinkAdExtension(extensionId, campaignId, initDisplayText, initDestinationUrl)
    		);
		
    	CampaignAdExtensionResponseParser parser = new CampaignAdExtensionResponseParser(resp);
    	responseErrorString = parser.checkForErrors();
	}//siteLinkExtensionRemoveOperation


    
    /*
     * Add operation
     */
    private boolean isChangesMade = true;
	protected void siteLinkExtensionAddOperation() {

    	if(!isChangesMade && extensionId != null)
    		return;
		
		String resp = Communication.postSOAP(
				CampaignAdExtensionService.URL_CAMPAIGN_AD_EXTENSION_SERVICE, 
				CampaignAdExtensionService.sitelinkExtensionOperation(campaignId, displayText, destinationUrl)
    		);

    	CampaignAdExtensionResponseParser parser = new CampaignAdExtensionResponseParser(resp);
    	responseErrorString = parser.checkForErrors();
    	
	}//siteLinkExtensionAddOperation

	

	/*
     * Save button handler
     */
    public void onClick_saveData(View v){
    	if(isDataValid()){
        	runOperationAsync(OPERATION_REMOVE_DATA, getString(R.string.progress_removing), false);
    	} else {
    		showOperationError(R.string.msg_title_invalid_data, formErrorString);
    	}	
    }//onClick_saveData


    
    /*
     * Validate form data
     */
	private boolean isDataValid() {
		
		boolean result = true;
		
		String displayTextValue;
		String destinationUrlValue;
		String urlSchema;
		
		int linkCount = ll_sitelinks.getChildCount();
		
		if(linkCount == 0){
			formErrorString = getString(R.string.msg_no_value);
			return false;
		}

		for(int i=0; i<linkCount; i++){
			View v = ll_sitelinks.getChildAt(i);
			
			EditText edit_sitelinkext_display = (EditText) v.findViewById(R.id.edit_sitelinkext_display);
			Spinner spin_sitelink_url_schema = (Spinner) v.findViewById(R.id.spin_sitelink_url_schema);
			EditText edit_sitelinkext_url = (EditText) v.findViewById(R.id.edit_sitelinkext_url);
			
			urlSchema = spin_sitelink_url_schema.getItemAtPosition(
					spin_sitelink_url_schema.getSelectedItemPosition()).toString();
			
			displayTextValue = edit_sitelinkext_display.getText().toString();
			destinationUrlValue = edit_sitelinkext_url.getText().toString();
			
			if(!destinationUrlValue.equals(""))
				destinationUrlValue = urlSchema + destinationUrlValue;
						
			// Validate data
			if(destinationUrlValue.equals("") && displayTextValue.equals("")){
	    		continue;
			} else if(!destinationUrlValue.equals("") && displayTextValue.equals("")){
	    		formErrorString = getString(R.string.msg_value_required);
	    		edit_sitelinkext_display.requestFocus();
	    		result = false;
	    		break;
	    	} else if(destinationUrlValue.equals("") && !displayTextValue.equals("")){
	    		formErrorString = getString(R.string.msg_value_required);
	    		edit_sitelinkext_url.requestFocus();
	    		result = false;
	    		break;	    		
	    	} else if(!DataValidator.isUrl(destinationUrlValue, true, true)){
	    		formErrorString = getString(R.string.msg_invalid_target_url);
	    		edit_sitelinkext_url.requestFocus();
	    		result = false;
	    		break;
	    	}
			
			displayText[i] = displayTextValue;
			destinationUrl[i] = destinationUrlValue;

		}
			
		// Erase inappropriate field
		for(int i = linkCount; i<10; i++){
			displayText[i] = null;
			destinationUrl[i] = null;
		}

		// Check if array element is null
		boolean empty = true;
		for (int i = 0; i < displayText.length; i++) {
			if (displayText[i] != null) {
				empty = false;
				break;
			}
		}
		
		if(empty && result){
			result = false;
			formErrorString = getString(R.string.msg_no_value);
		}
		
		return result;
	}//isDataValid
	
}
